package en.edu.zucc.pb.loginapplication.activity;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import en.edu.zucc.pb.loginapplication.R;
import en.edu.zucc.pb.loginapplication.categoryTab.FmPagerAdapter;
import en.edu.zucc.pb.loginapplication.categoryTab.TabFragment;
import en.edu.zucc.pb.loginapplication.db.Repository;
import en.edu.zucc.pb.loginapplication.entity.Record;
import en.edu.zucc.pb.loginapplication.gridIcons.GridIcons;
import en.edu.zucc.pb.loginapplication.gridIcons.IconButton;
//import en.edu.zucc.pb.loginapplication.model.Record;
import en.edu.zucc.pb.loginapplication.util.DateUtil;
import en.edu.zucc.pb.loginapplication.util.DrawUtil;
import en.edu.zucc.pb.loginapplication.util.PicUtil;
import en.edu.zucc.pb.loginapplication.widget.DatePick;
//import en.edu.zucc.pb.loginapplication.fragment.TabFragment;
//AppCompatActivity
//Activity 没有 get spport
public class TabActivity extends AppCompatActivity implements
        View.OnClickListener {
    private ArrayList<Fragment> fragments = new ArrayList<>();
//    private String[] titles = new String[]{"欧冠", "英超", "西甲", "意甲", "德甲",
//            "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};

    private String[] titles = new String[]{"支出", "收入"};


    Repository repository;

//    private RecyclerView rv;
//    private RvAdapter rvAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        setContentView(R.layout.activity_tab);
//        getvi
//        https://blog.csdn.net/lemisky/article/details/78413088
        init();
        initDatabase();

//        s(Context context, List< IconButton > iconButtons) {
        List<IconButton> iconButtons = new ArrayList<>();
//        Integer iconId;
//        String text;
//        iconButtons.add(new IconButton(R.drawable.ic_launcher_background,"icon"));

//        设置那两排的图标和文字
        iconButtons.add(new IconButton(R.drawable.icons8_french_fries_96, "餐饮食品"));
        iconButtons.add(new IconButton(R.drawable.icons8_clothes_96, "衣服饰品"));
        iconButtons.add(new IconButton(R.drawable.icons8_house_96, "居家生活"));
        iconButtons.add(new IconButton(R.drawable.icons8_traffic_light_96, "行车交通"));
        iconButtons.add(new IconButton(R.drawable.icons8_game_controller_96, "休闲娱乐"));
        iconButtons.add(new IconButton(R.drawable.icons8_scholarship_96, "文化教育"));
        iconButtons.add(new IconButton(R.drawable.icons8_medical_bag_96, "健康医疗"));

//        int num = 9;
        int num = 3;
        for (int i = 0; i < num; i++) {
            iconButtons.add(new IconButton(R.drawable.icons8_naruto_sign_144, "icon"));
        }


        gridIcons = new GridIcons(this, iconButtons);
        gridIcons.setTvShow(tvType);
//        设置点击了图标之后会显示文字的那个textview
        gridIcons.init();
//        gridIcons.init();
//        rv = (RecyclerView) findViewById(R.id.rv);
//        gridIcons.get

         picUtil = new PicUtil(this, ivShowPic);
//        picUtil.init();



    }
    PicUtil picUtil;

    //    https://blog.csdn.net/weixin_41008021/article/details/90346700
//    https://www.cnblogs.com/remix777/p/15416725.html
    private ArrayList<Uri> mSelected;
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
//            mSelected = (ArrayList<Uri>) Matisse.obtainResult(data);
//            Log.d("Matisse", "mSelected: " + mSelected);
//        }
//    }

//    启动了一个activity，然后activity结束之后，给我发了个requestCode，如果是REQUEST_CODE_CHOOSE
//    就是说选择成功了,就把读出来的图片给set一下
    int REQUEST_CODE_CHOOSE=1;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = (ArrayList<Uri>) Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);
//            picUtil.putPic(mSelected.get(0));
//            ivShowPic.
            ivShowPic.setImageURI(mSelected.get(0));
//            ivShowPic.bringToFront();
        }else{
            ivShowPic.setImageResource(R.drawable.icons8_picture_96);
        }
    }

    GridIcons gridIcons;

    /**
     * 初始化数据
     */

//    private void initData() {
//        datas = new ArrayList<>();
//        for (int i = 0; i < 38; i++) {
//            Resources res = getResources();
//            datas.add(res.getIdentifier("ic_category_" + i, "mipmap", getPackageName()));
//        }
//
//        /**
//         *用来确定每一个item如何进行排列摆放
//         * LinearLayoutManager 相当于ListView的效果
//         GridLayoutManager相当于GridView的效果
//         StaggeredGridLayoutManager 瀑布流
//         */
//        /**第一步：设置布局管理器**/
//        rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//        /**第二步：添加分割线**/
//        itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        rv.addItemDecoration(itemDecoration);
//        /**第三步：设置适配器**/
//        rvAdapter = new RvAdapter(this, datas);
//        rv.setAdapter(rvAdapter);
//        rvAdapter.setOnItemClickListener(new RvAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClickListener(int position, Integer data) {
//                Toast.makeText(MainActivity.this, "点击了" + position, Toast.LENGTH_SHORT).show();
//            }
//
//        });
//    }
//
//    void gridIcons(){
//        //        平铺的 很多个 的 按钮
//
//        new RvAdapter ();
//
//        /**竖向的GridView**/
////        case R.id.id_action_gridview:
//        rvAdapter.setType(1);
//        rv.setBackgroundColor(Color.TRANSPARENT);
//        rv.removeItemDecoration(itemDecoration);
//        rv.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
//        rv.setLayoutManager(new GridLayoutManager(this, 5));
//        itemDecoration = new DividerGridItemDecoration(this);
//        rv.addItemDecoration(itemDecoration);
//        break;
//
//    }
    TextView tvDate;
    EditText edMemo;
    EditText edPic;
    //    EditText edPos;
    TextView edPos;
//    TextView
    EditText edMoney;
    ImageView ivShowPic;
    Button btnSave;
    TextView tipTakePhoto;
    TextView tvType;
    private static final String TAG = "TabActivity";

    private void init() {
//        findViewById 在某个布局里
//        https://www.cnblogs.com/zhujiabin/p/5166056.html
//        View decorView = this.getWindow().getDecorView();
//        decorView.findViewById()

//        include 的话 就不能直接 find了
//        好像也不是这个问题。。
//        之前是因为从其他 layout里去find了。。
        View content_note_ll = findViewById(R.id.content_note_ll);
//        View ll_tab = findViewById(R.id.ll_tab);
//        Log.i(TAG,"content_note_ll : "+content_note_ll);

//        View content_note_ll = findViewById(R.id.content_note_ll);
//        btnSave = content_note_ll.findViewById(R.id.btnSave);
        btnSave = findViewById(R.id.btnSave);
//        btnSave.setli
//        btnSave.setOnClickListener(this);
        View ll_tab = content_note_ll.findViewById(R.id.ll_tab);
//        Log.i(TAG,"ll_tab : "+ll_tab);
//        ll_tab.findViewById()
//因为是 include 所以要 先找到这个 ll
//        TabLayout tabLayout =  ll_tab.findViewById(R.id.tab);
//        ViewPager viewPager = ll_tab. findViewById(R.id.viewpager);
//        content_note_ll.findViewById(R.id.edPos)
        View ll_item_note_post = content_note_ll.findViewById(R.id.ll_item_note_post);
        TabLayout tabLayout = ll_tab.findViewById(R.id.tab_layout);
        ViewPager viewPager = ll_tab.findViewById(R.id.viewPager);
//       ImageButton ibMicrophone= content_note_ll.findViewById(R.id. ibMicrophone);
        ImageButton ibMicrophone=findViewById(R.id. ibMicrophone);
        DrawUtil.setRoundImageDrawable(ibMicrophone,
                R.drawable.icons8_microphone_96, getResources(),
                50,50,20);
//        DrawUtil.roundBitmapByBitmapDrawable(ib)
        tvDate = ll_item_note_post.findViewById(R.id.tvDate);
        edMemo = ll_item_note_post.findViewById(R.id.edMemo);
//        edPic = ll_tab.findViewById(R.id.edPic);
        ivShowPic = ll_item_note_post.findViewById(R.id.ivShowPic);
        edPos = ll_item_note_post.findViewById(R.id.edPos);
        edMoney = ll_item_note_post.findViewById(R.id.edMoney);
        tipTakePhoto = ll_item_note_post.findViewById(R.id.tipTakePhoto);
//        edMoney = ll_item_note_post.findViewById(R.id.edPic);
        tvType= ll_item_note_post.findViewById(R.id.tvType);
//        tvType.setText();
        btnSave.setOnClickListener(this);
        tipTakePhoto.setOnClickListener(this);
        edMoney.setOnClickListener(this);
        edMemo.setOnClickListener(this);
        ibMicrophone.setOnClickListener(this);
//         tvDate = ll_tab.findViewById(R.id.tvDate);
//        edMemo = ll_tab.findViewById(R.id.edMemo);
////        edPic = ll_tab.findViewById(R.id.edPic);
//        ivShowPic = ll_tab.findViewById(R.id.ivShowPic);
//        edPos = ll_tab.findViewById(R.id.edPos);
//        edMoney = ll_tab.findViewById(R.id.edMoney);

//        要调用这个日期的选取的话， 就只要new 一个，然后  datePick.setShowDatePickOnClickListener(tvDate);
//        tvDate 就是他需要显示 日期的那个textView
        DatePick datePick = new DatePick(this);
//        datePick.showDatePickDlg();
        Log.i(TAG, "tvDate : " + tvDate);
        datePick.setShowDatePickOnClickListener(tvDate);


//        TabLayout tabLayout =  decorView.findViewById(R.id.tab);
//        ViewPager viewPager = decorView. findViewById(R.id.viewpager);
//        TabLayout tabLayout = findViewById(R.id.tab);
//        ViewPager viewPager = findViewById(R.id.viewpager);

        for (String title : titles) {
            fragments.add(new TabFragment(title));
        }

        FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        tabLayout.setupWithViewPager(viewPager);
//        findViewById(R.id.btnSave).setOnClickListener(this);

    }

    void initDatabase() {
        repository = new Repository(this);

    }


    void save() {
        String dateStr = tvDate.getText().toString();
        String memo = edMemo.getText().toString();
        String money = edMoney.getText().toString();
        String place = edPos.getText().toString();
//        String pic = edPic.getText().toString();
        String pic="pic";

        Record record = new Record();
        Log.i(TAG,"date: "+dateStr);
//        if(dateStr==null){
//            Toast.makeText(this, "没有日期", Toast.LENGTH_SHORT).show();
//            return;
//        }
        Date date = DateUtil.stringToDate(dateStr, DateUtil.ymdZh);

        if(date==null){
            Toast.makeText(this, "没有日期", Toast.LENGTH_SHORT).show();
            return;
        }

//        long time = DateUtil.stringToDate(dateStr, DateUtil.ymdZh).getTime();
        long time = date.getTime();
        IconButton selectedBtn = gridIcons.getSelectedBtn();
        if (selectedBtn == null) {
            Toast.makeText(this, "没有类型被选择，请选择类型", Toast.LENGTH_SHORT).show();
            return;
        }
//        除了 id 6个字段
//        record.setMemo(memo);
        record.setDateStamp(time);
        record.setMemo(memo);
        record.setMoney(Double.parseDouble(money));
        record.setPlace(place);
        record.setPic(pic);
        record.setTypeId(selectedBtn.getTypeId());
        Log.i(TAG,"record: "+record);
        repository.getRecordRepository().insert(record);
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

//    知乎的选择图片的api
    void pickPhoto(){
        //        ivShowPic
        Matisse.from(this) //Activity
                .choose(MimeType.ofAll()) //选择全部（包括视频）
                .countable(true)  // 有序选择图片
                .maxSelectable(9)  //最大选择数量为9
                .gridExpectedSize(400)  //图片显示表格的大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)  //缩放比率
                .theme(R.style.Matisse_Zhihu) //主题  暗色主题 R.style.Matisse_Dracula
                .imageEngine(new GlideEngine()) //加载方式
                .forResult(REQUEST_CODE_CHOOSE); //结果返回码 ，在onActivityResult中获取

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnSave:
                save();
                break;
            case R.id.tipTakePhoto:
                pickPhoto();
                break;

            case R.id.edMoney:
                if (edMoney.getText().toString().equals("多少钱")) {
                    edMoney.setText("");
                }

                break;
            case R.id.edMemo:
//                因为有默认hint 所以在选中的的时候 去掉默认的字
//                并且是在他是默认hint的情况下 其他 如果是已经填写好的东西，就点一下不会删掉
                if (edMemo.getText().toString().equals("备注")) {
                    edMemo.setText("");
                }
//                edMemo.setText("");
                break;


        }
    }

}
